import SocketServer
import tcpdaemon
import udpdaemon
import logger

# TODO: Set to True for release version
_is_daemon_ = False

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass
    
class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
    pass
   
def MainWork():
    # New logger
    logger = Log('Main', True)
    
    # Access to UdpDaemon and TcpDaemon through RequestHandlerClass member
    # of userver and tserver respectively.
    #
    userver = ThreadedUDPServer(('', 5000), UdpDaemon)
    tserver = ThreadedTCPServer(('', 5001), TcpDaemon)

    udp_server_thread = threading.Thread(target=userver.serve_forever)
    udp_server_thread.setDaemon(True)
    udp_server_thread.start()

    tcp_server_thread = threading.Thread(target=tserver.serve_forever)
    tcp_server_thread.setDaemon(True)
    tcp_server_thread.start()
    
    logger.log("Starting up . . .")

    while True:
        try:
            #TODO: Add work for main thread to consume
            pass
        except Exception as ex:
            logger.log("Main exception: ", ex)
            else:
                pass

    tserver.shutdown()
    userver.shutdown()
    
    logger.log("Shutting Down . . .")

if _isdaemon_:
    with daemon.DaemonContext():
        MainWork()
else:
    MainWork()


